let express = require("express");
let router = express.Router();
let path = require("path")
let fs = require("fs")

let svgcaptcha = require("svg-captcha")

//主页
router.get("/index", (req, res) => {
    //res.send("这是首页")
    //判断是否有登录 有登录，则进入到首页，没有登录，则先登录.
    console.log(req.cookies.username)
    res.render("index.html", {
        username: req.cookies.username
    })
    console.log(req.cookies.username);
})

router.get("/index", (req, res) => {
    res.render("./index.html");
})


let persons = fs.readFileSync(__dirname + "/persons.json", "utf8");
persons = JSON.parse(persons);

//登录
router.get("/login", (req, res) => {
    // console.log(111)
    res.render("login.html");
})

router.post("/login", (req, res) => {
    let { number, pswd } = req.body;
    let users = persons.find((item) => {
        //console.log(item);
        return number == item.username && pswd == item.password;
    })
    console.log(number,pswd,req.body);
    if (users) {
        //使用cookie记住用户
        res.cookie("username", number);
        res.redirect("/index");
    } else {
        res.send("密码或用户名错误");
    }
    // post 你那个是get 你的文件 都不对 对的呀  这个是中间
})

//注册
router.get("/register", (req, res) => {
    //res.send("登录")
    //登录时候使用cookie记住登录用户名
    //文本框提交的值
    res.render("register.html");
})

router.post("/register", (req, res) => {
    let { number, pswd, yzm } = req.body;
    console.log(req.body);
    let users = persons.find((item) => {
        return number == item.username
    })
    console.log(users);
    let data = {
        username: number,
        password: pswd
    };
    if (users) {
        res.send("用户已存在");
    } else {
        if (yzm == req.cookies.yzm1.toLowerCase()) {
            persons.push(data);
            persons = JSON.stringify(persons);
            fs.writeFileSync(__dirname + "/persons.json", persons, { flag: "w" })
            res.redirect("/login");
        } else {
            res.send("验证码错误");
        }

    }
})

//验证码
router.get("/yzm", (req, res) => {
    let captcha = svgcaptcha.create({});
    res.type("svg");
    res.cookie("yzm1", captcha.text)
    console.log(captcha.text);
    res.send(captcha.data);
})


module.exports = router